﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WorkSchedueSoft.Data;
using Timer = System.Threading.Timer;

namespace WorkSchedueSoft
{
    public partial class EditWin : Form
    {
        public PopWinMode current_popwin_mode;
        //public SchedueCommandItem current_command_info;

        public SchedueItem schedueitem;
        PopWinMode current_editwin_mode;

        public Dictionary<string, SchedueCommandItem> dict_schedue_command;

        mainForm main_win;

        int current_drag_index = 0;

        Timer timer;

        Point start_point;
        bool is_mouse_down;
        bool is_on_drag;

        public EditWin()
        {
            InitializeComponent();

            APPManager.Instance.Edit_win = this;

            timer = new Timer(new TimerCallback((t) => {
                if (is_mouse_down)
                {
                    Action action = () =>
                    {
                        var point = editlistBox.PointToClient(Control.MousePosition);
                        Point pp = new Point(point.X - start_point.X, point.Y - start_point.Y);
                        //double dis = Math.Sqrt(pp.X * pp.X + pp.Y * pp.Y);
                        //Console.WriteLine(pp.Y);
                        if (Math.Abs(pp.Y) > 4)
                        {
                            if (!is_on_drag)
                            {

                                is_on_drag = true;
                                if(editlistBox.SelectedItem != null)
                                    this.editlistBox.DoDragDrop(this.editlistBox.SelectedItem, DragDropEffects.Move);

                            }
                        }
                    };
                    Invoke(action);

                }
            }), null, 1000, 10);

            InitData();

            edit_win_contextMenuStrip.Items.Add("删除", null, deleteItem);
            edit_win_contextMenuStrip.Items.Add("添加", null, addItem);
            edit_win_contextMenuStrip.Items.Add("编辑", null, editItem);

            edit_win_contextMenuStrip1.Items.Add("添加", null, addItem);


        }

        public void InitData()
        {
            main_win = APPManager.Instance.Main_win;
            main_win.Enabled = false;
            current_editwin_mode = APPManager.Instance.current_editwin_mode;

            schedueitem = DataManager.Instance.Current_schedueitem;

            dict_schedue_command = new Dictionary<string, Data.SchedueCommandItem>();

            this.Text = current_editwin_mode == PopWinMode.ADD ? "添加Schedue" : "编辑Schedue";

            //如果是编辑模式，则加载和初始化当前编辑的条目
            if (current_editwin_mode == PopWinMode.EDIT)
            {
                RefreshData();
            }
            else if (current_editwin_mode == PopWinMode.ADD)
            {
                schedueitem = new SchedueItem() { name = "新的schedue", description = "默认描述" };
            }

            this.name_textBox.Text = schedueitem.name;
            this.description_textBox.Text = schedueitem.description;
        }

        public void RefreshData()
        {
            editlistBox.Items.Clear();

            if (schedueitem.commands != null && schedueitem.commands.Count > 0)
            {
                foreach (var item in schedueitem.commands)
                {
                    editlistBox.Items.Add(item.name);

                    if (!dict_schedue_command.ContainsKey(item.name))
                    {
                        dict_schedue_command.Add(item.name, item);
                    }
                }
            }

        }

        private void editItem(object sender, EventArgs e)
        {
            APPManager.Instance.current_commandwin_mode = PopWinMode.EDIT;
            int select_index = editlistBox.SelectedIndex;
            DataManager.Instance.Current_command_item =schedueitem.commands[select_index];
            CommandWin win = new CommandWin();
            win.Show();
        }

        private void addItem(object sender, EventArgs e)
        {
            APPManager.Instance.current_commandwin_mode= PopWinMode.ADD;
            DataManager.Instance.Current_command_item = new SchedueCommandItem() { name = "默认命令" };
            CommandWin commadnwin = new CommandWin();
            commadnwin.Show();
        }

        private void deleteItem(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除？", "删除", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                var selectedItem = editlistBox.SelectedItem;
                if (selectedItem != null)
                {
                    int index = editlistBox.SelectedIndex;
                    schedueitem.commands.RemoveAt(index);
                    RefreshData();
                }
            }
        }

        private void editlistBox_MouseUp(object sender, MouseEventArgs e)
        {

            is_mouse_down = false;
            is_on_drag = false;

            if (e.Button == MouseButtons.Right)
            {
                var point = new Point(e.X, e.Y);
                int posindex = editlistBox.IndexFromPoint(point);
                editlistBox.ContextMenuStrip = null;
                if (posindex >= 0 && posindex < editlistBox.Items.Count)
                {
                    editlistBox.SelectedIndex = posindex;
                    edit_win_contextMenuStrip.Show(editlistBox, point);
                }
                else
                {
                    edit_win_contextMenuStrip1.Show(editlistBox, point);
                }
            }
            editlistBox.Refresh();
        }

        private void okbutton_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(name_textBox.Text)) return;

            schedueitem.description = description_textBox.Text;
            schedueitem.name = name_textBox.Text;

            if (current_editwin_mode == PopWinMode.ADD)
            {

                if (!DataManager.Instance.Dict_schedue_items.ContainsKey(schedueitem.name))
                {
                    DataManager.Instance.Schedue_items.Add(this.schedueitem);
                    DataManager.Instance.RefreshData();
                }
                else
                {
                    MessageBox.Show("已经存在一个同名的了");
                    return;
                }

            }
            else if (current_editwin_mode == PopWinMode.EDIT)
            {
                DataManager.Instance.RefreshData();
            }

            main_win.RefreshData();

            this.Close();
        }

        private void cancelbutton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void editlistBox_DoubleClick(object sender, EventArgs e)
        {
            this.editItem(sender, e);
        }

        private void editlistBox_MouseMove(object sender, MouseEventArgs e)
        {
            int index = editlistBox.IndexFromPoint(e.Location);

            // 判断鼠标所在位置是否是有效元素
            if (index != -1 && index < editlistBox.Items.Count)
            {
                var current_command_item = DataManager.Instance.Current_command_item;
                if (current_command_item != null)
                {
                    if (toolTip1.GetToolTip(editlistBox) != current_command_item.description)
                        toolTip1.SetToolTip(editlistBox, current_command_item.description);
                }

            }
        }

        private void editlistBox_DragDrop(object sender, DragEventArgs e)
        {
            Point point = editlistBox.PointToClient(new Point(e.X, e.Y));
            int index = this.editlistBox.IndexFromPoint(point);
            if (index < 0)
            {
                index = this.editlistBox.Items.Count - 1;
            }
            //获取拖放的数据内容
            object data = e.Data.GetData(typeof(string));
            //删除原数据
            this.editlistBox.Items.Remove(data);
            //插入目标数据
            this.editlistBox.Items.Insert(index, data);

            //调整datamanager中的schedue列表排列
            var current_schedueitem = DataManager.Instance.Current_schedueitem;
            SchedueCommandItem oringin_item = current_schedueitem.commands[current_drag_index];
            current_schedueitem.commands.Remove(oringin_item);
            current_schedueitem.commands.Insert(index, oringin_item);
            RefreshData();

            //重置
            is_mouse_down = false;
            is_on_drag = false;

        }

        private void editlistBox_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void editlistBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
            {

                if (this.editlistBox.SelectedItem == null)
                {
                    return;
                }
                //开始拖放操作，DragDropEffects为枚举类型。
                //DragDropEffects.Move 为将源数据移动到目标数据
                is_mouse_down = true;
                start_point = e.Location;
                this.current_drag_index = editlistBox.SelectedIndex;
            }
        }
    }

    
}
